#!/bin/bash

# Update script for Hysteria

set -e

echo "Updating Hysteria..."

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "Please run as root (use sudo)"
    exit 1
fi

# Backup current version
echo "Backing up current version..."
cp /usr/local/bin/hysteria /usr/local/bin/hysteria.backup

# Stop services
echo "Stopping services..."
systemctl stop hysteria hysteria-admin

# Download latest version
echo "Downloading latest version..."
DOWNLOAD_URL="https://github.com/your-repo/hysteria-rust/releases/latest/download"
OS="$(uname -s)"

case "$OS" in
    Linux)
        BINARY_NAME="hysteria-linux-amd64"
        ;;
    Darwin)
        BINARY_NAME="hysteria-macos-amd64"
        ;;
    *)
        echo "Unsupported OS: $OS"
        exit 1
        ;;
esac

curl -L "$DOWNLOAD_URL/$BINARY_NAME" -o /tmp/hysteria

# Install new version
echo "Installing new version..."
chmod +x /tmp/hysteria
mv /tmp/hysteria /usr/local/bin/hysteria

# Start services
echo "Starting services..."
systemctl start hysteria hysteria-admin

# Check status
sleep 2
if systemctl is-active --quiet hysteria; then
    echo "Update completed successfully!"
    echo "New version: $(/usr/local/bin/hysteria version)"
else
    echo "Update failed! Rolling back..."
    mv /usr/local/bin/hysteria.backup /usr/local/bin/hysteria
    systemctl start hysteria hysteria-admin
    exit 1
fi
